<!-- eslint-disable -->
<template>
  <el-card v-loading="isLoading" element-loading-text="正在加载数据，请稍候...">
    <template #header>
      <div>配置转发规则</div>
    </template>
    <div class="error-content" v-if="loadError">
      <el-icon class="error-icon"><CircleClose /></el-icon>
      <p>{{ loadError }}</p>
      <el-button type="primary" @click="loadData">重新加载</el-button>
    </div>
    <template v-else>
      <!-- 数据加载成功后显示配置界面 -->
      <el-card class="rule-card">
        <template #header>
          <div class="rule-header">
            <h3>消息来源设置</h3>
          </div>
        </template>

        <el-form label-position="top">
          <!-- 来源类型选择 -->
          <el-form-item label="来源类型">
            <el-radio-group
              v-model="sourceType"
              @change="handleSourceTypeChange"
            >
              <el-radio-button label="group">群聊</el-radio-button>
              <el-radio-button label="friend">好友</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <!-- 来源群聊选择 -->
          <el-form-item v-if="sourceType === 'group'" label="选择群聊">
            <el-select
              v-model="selectedGroupId"
              filterable
              placeholder="选择群聊"
              :loading="transferStore.loading.groups"
              class="wide-select"
              @change="handleGroupChange"
              value-key="wx_id"
            >
              <el-option
                v-for="group in transferStore.groups"
                :key="group.wx_id"
                :label="group.nick_name"
                :value="group.wx_id"
              >
                <div class="option-content">
                  <el-avatar
                    v-if="group.avatar_url"
                    :src="group.avatar_url"
                    :size="30"
                  ></el-avatar>
                  <el-avatar v-else :size="30">{{
                    group.nick_name.substring(0, 1)
                  }}</el-avatar>
                  <span class="option-label">{{ group.nick_name }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 来源群成员选择 -->
          <el-form-item
            v-if="sourceType === 'group' && selectedGroupId"
            label="选择群成员 (可选)"
          >
            <el-select
              v-model="selectedGroupMemberId"
              filterable
              placeholder="选择群成员 (不选择则转发群内所有消息)"
              :loading="isLoadingGroupMembers"
              class="wide-select"
              clearable
            >
              <el-option
                v-for="member in groupMembers"
                :key="member.wx_id"
                :label="member.nick_name || member.remark || member.wx_id"
                :value="member.wx_id"
              >
                <div class="option-content">
                  <el-avatar
                    v-if="member.avatar_url"
                    :src="member.avatar_url"
                    :size="30"
                  ></el-avatar>
                  <el-avatar v-else :size="30">{{
                    (
                      member.nick_name ||
                      member.remark ||
                      member.wx_id
                    ).substring(0, 1)
                  }}</el-avatar>
                  <span class="option-label">{{
                    member.nick_name || member.remark || member.wx_id
                  }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 来源好友选择 -->
          <el-form-item v-if="sourceType === 'friend'" label="选择好友">
            <el-select
              v-model="selectedFriendId"
              filterable
              placeholder="选择好友"
              :loading="transferStore.loading.friends"
              class="wide-select"
            >
              <el-option
                v-for="friend in transferStore.friends"
                :key="friend.wx_id"
                :label="friend.nick_name || friend.remark || friend.wx_id"
                :value="friend.wx_id"
              >
                <div class="option-content">
                  <el-avatar
                    v-if="friend.avatar_url"
                    :src="friend.avatar_url"
                    :size="30"
                  ></el-avatar>
                  <el-avatar v-else :size="30">{{
                    (
                      friend.nick_name ||
                      friend.remark ||
                      friend.wx_id
                    ).substring(0, 1)
                  }}</el-avatar>
                  <span class="option-label">{{
                    friend.nick_name || friend.remark || friend.wx_id
                  }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="rule-card">
        <template #header>
          <div class="rule-header">
            <h3>转发目标设置</h3>
          </div>
        </template>

        <el-form label-position="top">
          <!-- 转发目标穿梭框 -->
          <el-form-item label="选择转发目标">
            <el-transfer
              v-model="selectedTargets"
              :data="transferTargets"
              :titles="['可选转发目标', '已选转发目标']"
              :button-texts="['移除', '添加']"
              filterable
              filter-placeholder="搜索联系人或群组"
              :props="{
                key: 'wx_id',
                label: 'label',
              }"
            >
              <template #default="{ option }">
                <div class="transfer-item">
                  <el-avatar
                    v-if="option.avatar_url"
                    :src="option.avatar_url"
                    :size="30"
                  ></el-avatar>
                  <el-avatar v-else :size="30">{{
                    option.label.substring(0, 1)
                  }}</el-avatar>
                  <span class="transfer-label">{{ option.label }}</span>
                  <el-tag
                    size="small"
                    :type="option.isGroup ? 'success' : 'info'"
                  >
                    {{ option.isGroup ? "群聊" : "好友" }}
                  </el-tag>
                </div>
              </template>
            </el-transfer>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="rule-card">
        <template #header>
          <div class="rule-header">
            <h3>消息过滤设置</h3>
          </div>
        </template>

        <el-form label-position="top">
          <!-- 消息类型过滤器 -->
          <el-form-item label="转发的消息类型">
            <el-checkbox-group v-model="selectedContentTypes">
              <el-checkbox label="text">文本消息</el-checkbox>
              <el-checkbox label="image">图片消息</el-checkbox>
              <el-checkbox label="video">视频消息</el-checkbox>
              <el-checkbox label="file">文件消息</el-checkbox>
              <el-checkbox label="voice">语音消息</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <!-- 关键词过滤器 -->
          <el-form-item label="关键词过滤 (可选)">
            <el-input
              v-model="keywordFilter"
              placeholder="输入关键词，多个关键词用英文逗号分隔"
              class="wide-input"
              clearable
            />
            <div class="hint-text">
              只转发包含指定关键词的消息，留空则转发所有符合类型的消息
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <div class="rule-actions">
        <el-button type="primary" :loading="isSaving" @click="saveRule">
          保存规则
        </el-button>
      </div>
    </template>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useTransferStore } from "../store/transferStore";
import { useLogStore } from "../store/logStore";
import { CircleClose, Loading } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

// ESLint禁用下一行检查
// eslint-disable-next-line no-undef
const props = defineProps({
  port: {
    type: Number,
    default: 8989,
  },
});

// 使用store
const transferStore = useTransferStore();
const logStore = useLogStore();

// 本地状态
const isLoading = ref(true);
const loadError = ref("");
const isSaving = ref(false);
const isLoadingGroupMembers = ref(false);

// 来源设置
const sourceType = ref("group"); // 'group' 或 'friend'
const selectedGroupId = ref("");
const selectedGroupMemberId = ref("");
const selectedFriendId = ref("");
const groupMembers = ref([]);

// 目标设置
const selectedTargets = ref([]);

// 过滤设置
const selectedContentTypes = ref(["text", "image"]);
const keywordFilter = ref("");

// 计算属性
const transferTargets = computed(() => {
  // 组合所有好友和群聊为穿梭框数据源
  const targets = [
    ...transferStore.friends.map((friend) => ({
      wx_id: friend.wx_id,
      avatar_url: friend.avatar_url,
      label: friend.nick_name || friend.remark || friend.wx_id,
      isGroup: false,
      raw: friend,
    })),
    ...transferStore.groups.map((group) => ({
      wx_id: group.wx_id,
      avatar_url: group.avatar_url,
      label: group.nick_name || group.wx_id,
      isGroup: true,
      raw: group,
    })),
  ];

  return targets;
});

// 监听端口变化
watch(
  () => props.port,
  (newPort) => {
    if (newPort) {
      transferStore.setPort(newPort);
      loadData();
    }
  }
);

// 处理来源类型变化
const handleSourceTypeChange = () => {
  // 重置相关选择
  selectedGroupId.value = "";
  selectedGroupMemberId.value = "";
  selectedFriendId.value = "";
  groupMembers.value = [];
};

// 处理群聊选择变化
const handleGroupChange = async (groupId) => {
  if (!groupId) {
    groupMembers.value = [];
    selectedGroupMemberId.value = "";
    return;
  }

  // 加载群成员
  isLoadingGroupMembers.value = true;
  try {
    // 检查是否有缓存
    if (transferStore.groupMembers[groupId]) {
      groupMembers.value = transferStore.groupMembers[groupId];
    } else {
      // 如果没有缓存，则调用API加载
      await transferStore.loadGroupMembers(groupId, props.port);
      groupMembers.value = transferStore.groupMembers[groupId] || [];
    }
  } catch (error) {
    ElMessage.error(`加载群成员失败: ${error.message}`);
    logStore.addMessage(`加载群成员失败: ${error.message}`);
    groupMembers.value = [];
  } finally {
    isLoadingGroupMembers.value = false;
  }
};

// 保存规则
const saveRule = async () => {
  // 验证必填项
  if (sourceType.value === "group" && !selectedGroupId.value) {
    ElMessage.warning("请选择来源群聊");
    return;
  }

  if (sourceType.value === "friend" && !selectedFriendId.value) {
    ElMessage.warning("请选择来源好友");
    return;
  }

  if (selectedTargets.value.length === 0) {
    ElMessage.warning("请选择至少一个转发目标");
    return;
  }

  if (selectedContentTypes.value.length === 0) {
    ElMessage.warning("请选择至少一种转发消息类型");
    return;
  }

  isSaving.value = true;

  try {
    // 构造规则对象
    const rule = {
      sourceType: sourceType.value,
      source:
        sourceType.value === "group"
          ? selectedGroupId.value
          : selectedFriendId.value,
      sourceMember: selectedGroupMemberId.value || null,
      targets: selectedTargets.value,
      contentTypes: selectedContentTypes.value,
      keywords: keywordFilter.value
        ? keywordFilter.value.split(",").map((k) => k.trim())
        : [],
      enabled: true,
      port: props.port,
    };

    // 保存规则到store
    transferStore.addRule(rule);
    logStore.addMessage(
      `转发规则已保存: ${sourceType.value === "group" ? "群聊" : "好友"} -> ${
        selectedTargets.value.length
      }个目标`
    );

    // 显示成功消息
    ElMessage.success("转发规则保存成功");

    // 清空表单，准备添加下一条规则
    resetForm();
  } catch (error) {
    ElMessage.error(`保存规则失败: ${error.message}`);
    logStore.addMessage(`保存规则失败: ${error.message}`);
  } finally {
    isSaving.value = false;
  }
};

// 重置表单
const resetForm = () => {
  sourceType.value = "group";
  selectedGroupId.value = "";
  selectedGroupMemberId.value = "";
  selectedFriendId.value = "";
  selectedTargets.value = [];
  keywordFilter.value = "";
};

// 加载数据
const loadData = async () => {
  isLoading.value = true;
  loadError.value = "";

  try {
    // 设置端口号
    transferStore.setPort(props.port);

    // 加载数据
    logStore.addMessage(`正在加载联系人和群组数据，端口号: ${props.port}`);
    await transferStore.loadAllData(props.port);
    logStore.addMessage(
      `成功加载 ${transferStore.friends.length} 个联系人和 ${transferStore.groups.length} 个群组`
    );
  } catch (error) {
    loadError.value = `加载数据失败: ${error.message}`;
    logStore.addMessage(loadError.value);
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.transfer-rules {
  padding: 20px;
}

.rule-card {
  margin-bottom: 20px;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rule-header h3 {
  margin: 0;
}

.wide-select,
.wide-input {
  width: 100%;
}

.option-content {
  display: flex;
  align-items: center;
}

.option-label {
  margin-left: 10px;
}

.transfer-item {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.transfer-label {
  margin: 0 10px;
  flex: 1;
}

.rule-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.loading-card,
.error-card {
  padding: 30px;
  text-align: center;
}

.loading-content,
.error-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-icon {
  font-size: 24px;
  animation: rotating 2s linear infinite;
}

.error-icon {
  font-size: 24px;
  color: #f56c6c;
}

.hint-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
